import type { AreaNode } from '@/api/login.typings'
import { areas } from '@/api/login.typings'

// 转换地区数据
export const transformAreas = (areas: AreaNode[]) => {
  const district: Record<string, Array<{ label: string; value: string }>> = {
    '0': [],
  }

  const codeToNameMap: Record<string, string> = {}

  areas.forEach((province) => {
    const provCode = province.code.padEnd(6, '0')
    district['0'].push({ label: province.name, value: provCode })
    codeToNameMap[provCode] = province.name

    district[provCode] = []
    province.children?.forEach((city) => {
      const cityCode = city.code.padEnd(6, '0')
      district[provCode].push({ label: city.name, value: cityCode })
      codeToNameMap[cityCode] = city.name

      district[cityCode] = []
      city.children?.forEach((area) => {
        district[cityCode].push({ label: area.name, value: area.code })
        codeToNameMap[area.code] = area.name
      })
    })
  })

  return { district, codeToNameMap }
}

// 查找地址编码
export const findAddressCodes = (provinceName: string, cityName: string, countryName: string) => {
  const result = {
    provinceCode: '',
    cityCode: '',
    countryCode: '',
  }

  const province = areas.find((p) => p.name === provinceName)
  if (!province) return result

  result.provinceCode = province.code.padEnd(6, '0')

  const city = province.children?.find((c) => c.name === cityName)
  if (!city) return result

  result.cityCode = city.code.padEnd(6, '0')

  const area = city.children?.find((a) => a.name === countryName)
  if (area) result.countryCode = area.code

  return result
}

// 公共导出数据
export const { district, codeToNameMap } = transformAreas(areas)
